export const querystring = {
    stringify: (params: any) => {
        return Object.keys(params).map(k => `${k}=${params[k]}`).join('&')
    }
}
const url_base = location.pathname + '/'
export const Fetch = (url: string, params?: any, method = 'POST') => fetch(url_base + url, {
    credentials: 'same-origin',
    method,
    headers: {
        'x-requested-with': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: params && querystring.stringify(params)
}).then(res => {
    if (res.redirected) {
        location.reload()
    } else {
        return res.json()
    }
})


export const allInfo = () => Fetch('allInfo', null, 'GET')
export const loginUser = () => Fetch('loginUser', null, 'GET')

export const addRole = (name: string) => Fetch('addRole', { name })
export const changePassword = ({ pw0, pw1, pw2 }) => Fetch('changePassword', { pw0, pw1, pw2 })
export const avatarUpdate = ({ avatar }) => Fetch('avatarUpdate', { avatar })
export const updateRoleAuthority = ({ roleId, authorityId, level }) => Fetch('updateRoleAuthority', { roleId, authorityId, level })
export const updateUserRole = ({ userId, roleId }) => Fetch('updateUserRole', { userId, roleId })
export const addUser = ({ name, password, nickname }) => Fetch('addUser', { name, password, nickname })
export const delRole = (roleId: number) => Fetch('delRole', { roleId })
export const updateUserLockIPs = ({ userId, ips }) => Fetch('updateUserLockIPs', { userId, ips })
export const updateUserExpires = ({ userId, expires }) => Fetch('updateUserExpires', { userId, expires })
export const delUser = (userId: number) => Fetch('delUser', { userId })
export const resetPassword = (userId: number, password: string) => Fetch('resetPassword', { userId, password })
